<?php
/*
 * @Description: 账户服务
 * @Author: franktrue 807615827@qq.com
 * @Date: 2021-07-13 12:45:54
 * @LastEditTime: 2021-07-13 13:04:49
 */
namespace App\Rpc\Service;

use App\Model\Entity\AccountUser;
use App\Rpc\Lib\AccountUserInterface;
use Swoft\Rpc\Server\Annotation\Mapping\Service;

/**
 * Class AccountUserService
 *
 * @since 2.0
 *
 * @Service()
 */
class AccountUserService implements AccountUserInterface
{
    /**
     * 注册账户
     * 
     * @param string $type 账户类型 username/email/phone
     * @param string $account 账户名
     * @param string $password 密码
     * @param string $createIpAt 创建者IP地址
     * 
     * @return array
     */
    public function register(string $type, string $account, string $password, string $createIpAt = ''): array
    {
        try{
            $user = new AccountUser();
            $method = 'set' . ucfirst($type);
            $user->$method($account);
            $user->setPassword($password);
            $user->setCreateIpAt($createIpAt);
            $user->save();
            return ['code' => 0, 'msg' => '注册成功', 'data' => $user];
        }catch (\Exception $e){
            return ['code' => -1, 'msg' => $e->getMessage()];
        }
    }

    /**
     * 登路账户
     * 
     * @param string $type 账户类型 username/email/phone
     * @param string $account 账户名
     * @param string $password 密码
     * @param string $lastLoginIpAt 创建者IP地址
     * 
     * @return array
     */
    public function login(string $type, string $account, string $password, string $lastLoginIpAt = ''): array
    {
        $user = AccountUser::where($type, $account)->first();
        if($user && $user->check($password)) {
            $user->increment('login_times', 1, [
                'last_login_at' => time(), 
                'last_login_ip_at' => $lastLoginIpAt]
            );
            return ['code' => 0, 'msg' => '登路成功', 'data' => $user];
        }
        return ['code' => -1, 'msg' => '账户名或密码错误'];
    }

    /**
     * @param int $id
     * @param array $columns
     * 
     * @return array
     */
    public function get(int $id, array $columns = ['*']): array
    {
        return AccountUser::find($id, $columns)->toArray();
    }

    /**
     * @param int $id
     * @param array $attributes
     * 
     * @return bool
     */
    public function update(int $id, array $attributes): bool
    {
        return AccountUser::find($id)->update($attributes);
    }

    /**
     * @param int $id
     * 
     * @return bool
     */
    public function delete($id): bool
    {
        return AccountUser::find($id)->update(['status' => 1]);
    }
}